package com.gutsyzhan.bilibili.service.impl;

import com.gutsyzhan.bilibili.constant.AuthRoleConstant;
import com.gutsyzhan.bilibili.domain.auth.*;
import com.gutsyzhan.bilibili.service.AuthRoleService;
import com.gutsyzhan.bilibili.service.UserAuthService;
import com.gutsyzhan.bilibili.service.UserRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Resource
    private UserRoleService userRoleService;

    @Resource
    private AuthRoleService authRoleService;

    @Override
    public UserAuthorities getUserAuthorities(Long userId) {
        List<UserRole> userRoleLists = userRoleService.getUserRoleByUserId(userId);
        Set<Long> roleIdSet = userRoleLists.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        //查询操作权限
        List<AuthRoleElementOperation> roleElementOperationList = authRoleService.getRoleElementOperationByRoleIds(roleIdSet);
        //查询菜单权限
        List<AuthRoleMenu> roleMenuList = authRoleService.getRoleMenuByRoleIds(roleIdSet);
        //构造返回权限对象
        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleElementOperationList(roleElementOperationList);
        userAuthorities.setRoleMenuList(roleMenuList);
        return userAuthorities;
    }

    @Override
    public void addUserDefaultRole(Long id) {
        Date now = new Date();
        String defaultRoleCode = AuthRoleConstant.ROLE_LV0;
        UserRole userRole = new UserRole();
        AuthRole authRole = authRoleService.getRoleByCode(defaultRoleCode);
        userRole.setUserId(id);
        userRole.setRoleId(authRole.getId());
        userRole.setCreateTime(now);
        userRole.setUpdateTime(now);
        userRoleService.addUserRole(userRole);
    }
}
